<template>
  <div>
    <el-dialog
      v-model="show"
      :title="title"
      width="500"
      draggable
      destroy-on-close
      @close="reset"
    >
      <div>
        <el-form
          :model="formData"
          label-width="auto"
          style="max-width: 600px"
          :rules="rules"
          ref="ruleForm"
          :mode="ruleModel"
        >
          <el-form-item label="公告标题" prop="title">
            <el-input v-model="formData.title" />
          </el-form-item>
          <el-form-item label="字段类型">
            <el-select v-model="formData.type" placeholder="请输入公告类型">
              <el-option label="通知" value="0" />
              <el-option label="公告" value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-radio-group v-model="formData.status">
              <el-radio value="0">禁用</el-radio>
              <el-radio value="1">启用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="公告内容" prop="content">
            <el-input
              v-model="formData.content"
              type="textarea"
              maxlength="2000"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="reset">取消</el-button>
          <el-button type="primary" @click="onSubmit"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { defineExpose, ref, defineEmits } from "vue";

const emits = defineEmits(["common"]);
const show = ref(false);
const title = ref("添加公告");

const ruleForm = ref();
const rules = ref({
  title: [{ required: true, message: "请输入公告标题", trigger: "blur" }],
  content: [{ required: true, message: "请输入公告内容", trigger: "blur" }],
});

const formData = ref({
  id: null,
  title: "",
  content: "",
  status: "1",
  type: "0",
  flag: 1,
});

const open = (item, type) => {
  show.value = true;
  title.value = type;
  if ("修改公告" === type) {
    formData.value.id = item.id;
    formData.value.title = item.title;
    formData.value.content = item.content;
    formData.value.status = item.status == 0 ? "0" : "1";
    formData.value.type = item.type === 1 ? "1" : "0";
    formData.value.flag = 0;
  }
};

const ruleModel = ref({
  title: "",
  content: "",
});

const onSubmit = () => {
  ruleForm.value.validate((valid) => {
    if (valid) {
      emits("common", formData.value);
      reset();
    }
  });
};

const reset = () => {
  formData.value = {
    id: null,
    title: "",
    content: "",
    status: "1",
    type: "0",
    flag: 1,
  };
  show.value = false;
};

defineExpose({
  open,
});
</script>

<style></style>
